/**
 * Free software.
 */

package org.nanhill.support.lucene.simplesearch;

import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Searcher;
import org.nanhill.TestUtil;

/**
 * @author alin [xalinx at gmail dot com]
 * @date 2006-10-12
 */
public class SimpleSearch {

	/**
	 * @param args
	 * @throws IOException
	 * @throws ParseException
	 * @throws InterruptedException
	 */
	public static void main(String[] args) throws IOException, ParseException,
			InterruptedException {
		String indexdir = TestUtil.getRoot() + "/lucene/simplesearch";
		Analyzer analyser = new StandardAnalyzer();
		IndexWriter writer = new IndexWriter(indexdir, analyser, true);
		Document doc = new Document();
		doc.add(new Field("title", "test 测试 china", Field.Store.YES,
				Field.Index.TOKENIZED));
		doc.add(new Field("id", "you 测试 北京 me let test? ", Field.Store.NO,
				Field.Index.TOKENIZED));
		Document doc2 = new Document();
		doc2.add(new Field("title", "test china 2", Field.Store.YES,
				Field.Index.TOKENIZED));
		doc2.add(new Field("id", "what test 测试 me ina 2", Field.Store.NO,
				Field.Index.TOKENIZED));
		writer.addDocument(doc);
		writer.addDocument(doc2);
		writer.optimize();
		writer.close();

		Searcher searcher = new IndexSearcher(indexdir);
		QueryParser parser = new QueryParser("id", analyser);
		Query query = parser.parse("北京人");
		Hits hits = searcher.search(query);
		for (int i = 0; i < hits.length(); i++) {
			Document hitdoc = hits.doc(i);
			String value = hitdoc.get("id");
			System.out.print(i + ">> id:" + value);
			value = hitdoc.get("title");
			System.out.println("|title:" + value);
		}
	}
}
